/*******************************************************************************
 * Copyright (c) 2018, 2018 Grimm
 ******************************************************************************/
package com.alex.java8_03;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

import org.junit.Test;

/**
 * Java8内置四大核心接口：
 * 1.消费型接口：Consumer<T>
 * void accept(T t)
 * 2.供给型接口：Supplier<T>
 * T get()
 * 3.函数型接：Function(T R)
 * R apply(T t)
 * 4.断言型接口：Predicate(T)
 * boolean test(T t)
 */
public class TestLambda3 {

	// Consumer<T>: 消费型接口
	@Test
	public void test1() {
		happy(100.00, (m) -> System.out.println("你们刚哥喜欢大宝剑 ，每次消费：" + m + "元"));
	}

	private void happy(double money, Consumer<Double> con) {
		con.accept(money);
	}

	// Supplier<T>: 供给型接口
	@Test
	public void test2() {
		List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
		numList.forEach(System.out::println);
	}

	// 需求：生产指定个数(num)的整数，并放入集合中
	private List<Integer> getNumList(int num, Supplier<Integer> sup) {
		List<Integer> list = new ArrayList<>();
		for (int i = 0; i < num; i++) {
			list.add(sup.get());
		}
		sup.get();
		return list;
	}

	// Function(T R)：函数型接口
	@Test
	public void test3() {
		String newStr = strHandler("hirain  Technology", (str) -> str.trim().replaceAll(" ", ""));
		System.out.println(newStr);
	}

	// 需求：用于处理字符串
	private String strHandler(String str, Function<String, String> fun) {
		return fun.apply(str);
	}

	// Predicate(T): 断言型接口
	@Test
	public void test4() {
		List<String> strList = Arrays.asList("aliex", "bob", "cat", "david", "ellen", "folien");
		List<String> filterStr = filterStr(strList, (str) -> str.length() == 3);
		filterStr.forEach(System.out::println);
	}

	// 需求：将满足条件的字符串放入集合中
	private List<String> filterStr(List<String> strList, Predicate<String> pre) {
		List<String> list = new ArrayList<>();
		for (String str : strList) {
			if (pre.test(str)) {
				list.add(str);
			}
		}
		return list;
	}
}
